package com.luoguijia.disk.login.control;

import com.luoguijia.disk.login.service.LoginService;
import com.luoguijia.disk.mybatis.entity.PtUserEntity;
import com.luoguijia.disk.spring.security.UserDiskEntity;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class PasswordController {

    @Resource
    private LoginService loginService;

    @Resource
    private MessageSource messageSource;

    @Resource
    private PasswordEncoder passwordEncoder;

    // 跳转密码页（保持不变）
    @RequestMapping(value = "/toPasswordPage", method = RequestMethod.GET)
    public String toPasswordPage() {
        return "login/passwordPage";
    }

    // 处理密码修改（明确指定POST方法）
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updatePassword(
            @RequestParam("oldPassword") String oldPassword,
            @RequestParam("newPassword") String newPassword,
            @RequestParam("confirmPassword") String confirmPassword) {

        Map<String, Object> result = new HashMap<>();
        try {
            // 1. 验证当前用户是否登录
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (!(principal instanceof UserDiskEntity)) {
                result.put("success", false);
                result.put("message", "未登录或登录已失效");
                return result;
            }

            // 2. 获取用户信息
            UserDiskEntity currentUser = (UserDiskEntity) principal;
            PtUserEntity dbUser = loginService.queryUserInfoByName(currentUser.getUsername());
            if (dbUser == null) {
                throw new UsernameNotFoundException("用户不存在");
            }

            // 3. 验证新密码一致性
            if (!newPassword.equals(confirmPassword)) {
                result.put("success", false);
                result.put("message", messageSource.getMessage(
                        "password.not.match", null, LocaleContextHolder.getLocale()
                ));
                return result;
            }

            // 4. 验证旧密码
            if (!passwordEncoder.matches(oldPassword, dbUser.getPassword())) {
                result.put("success", false);
                result.put("message", messageSource.getMessage(
                        "password.old.wrong", null, LocaleContextHolder.getLocale()
                ));
                return result;
            }

            // 5. 检查新密码是否与旧密码相同
            if (passwordEncoder.matches(newPassword, dbUser.getPassword())) {
                result.put("success", false);
                result.put("message", "新密码不能与旧密码相同");
                return result;
            }

            // 6. 更新密码
            String encodedNewPassword = passwordEncoder.encode(newPassword);
            loginService.updatePassword(dbUser.getUserUuid(), encodedNewPassword);

            // 6. 返回成功结果
            result.put("success", true);
            result.put("message", messageSource.getMessage(
                    "password.modify.success", null, LocaleContextHolder.getLocale()
            ));
            result.put("redirect", "/disk/");

        } catch (Exception e) {
            // 捕获所有异常并返回详细信息
            result.put("success", false);
            result.put("message", messageSource.getMessage(
                    "password.modify.fail", null, LocaleContextHolder.getLocale()
            ) + ": " + e.getMessage());
            // 打印异常堆栈到控制台（关键排查依据）
            e.printStackTrace();
        }
        return result;
    }

}